import subprocess
import os
import sys
import time
import threading
import webbrowser
from http.server import HTTPServer, SimpleHTTPRequestHandler

# 项目根目录
PROJECT_DIR = os.path.dirname(os.path.abspath(__file__))

# HTTP服务器端口
HTTP_PORT = 8000

# 启动HTTP服务器
def start_http_server():
    # 切换到项目目录作为服务器根目录
    os.chdir(PROJECT_DIR)
    
    # 创建HTTP服务器
    server_address = ('', HTTP_PORT)
    httpd = HTTPServer(server_address, SimpleHTTPRequestHandler)
    
    print(f"HTTP服务器已启动，访问: http://localhost:{HTTP_PORT}")
    
    # 在默认浏览器中打开投屏页面
    webbrowser.open(f"http://localhost:{HTTP_PORT}")
    
    try:
        # 启动服务器
        httpd.serve_forever()
    except KeyboardInterrupt:
        print("HTTP服务器已停止")
    finally:
        httpd.server_close()

# 启动simple_stream.py
def start_simple_stream():
    simple_stream_path = os.path.join(PROJECT_DIR, 'simple_stream.py')
    
    if not os.path.exists(simple_stream_path):
        print(f"错误: 找不到simple_stream.py文件: {simple_stream_path}")
        return None
    
    print("启动simple_stream.py...")
    
    # 启动simple_stream.py进程
    process = subprocess.Popen(
        [sys.executable, simple_stream_path],
        stdout=subprocess.PIPE,
        stderr=subprocess.STDOUT,
        text=True
    )
    
    # 监控进程输出
    def monitor_output():
        while True:
            try:
                # 尝试读取一行输出
                line = process.stdout.readline()
                if not line and process.poll() is not None:
                    break
                if line:
                    # 尝试解码输出，如果失败则使用错误处理模式
                    try:
                        decoded_line = line.strip()
                    except UnicodeDecodeError:
                        decoded_line = line.decode('utf-8', errors='ignore').strip()
                    print(f"[simple_stream] {decoded_line}")
            except Exception as e:
                print(f"读取simple_stream输出时出错: {e}")
        
        if process.poll() != 0:
            print(f"警告: simple_stream.py进程异常退出，返回代码: {process.returncode}")
    
    # 启动监控线程
    monitor_thread = threading.Thread(target=monitor_output)
    monitor_thread.daemon = True
    monitor_thread.start()
    
    return process

# 启动websocket_server.py
def start_websocket_server():
    websocket_server_path = os.path.join(PROJECT_DIR, 'websocket_server.py')
    
    if not os.path.exists(websocket_server_path):
        print(f"警告: 找不到websocket_server.py文件: {websocket_server_path}")
        return None
    
    print("启动websocket_server.py...")
    
    # 启动websocket_server.py进程
    process = subprocess.Popen(
        [sys.executable, websocket_server_path],
        stdout=subprocess.PIPE,
        stderr=subprocess.STDOUT,
        text=True
    )
    
    # 监控进程输出
    def monitor_output():
        while True:
            try:
                # 尝试读取一行输出
                line = process.stdout.readline()
                if not line and process.poll() is not None:
                    break
                if line:
                    # 尝试解码输出，如果失败则使用错误处理模式
                    try:
                        decoded_line = line.strip()
                    except UnicodeDecodeError:
                        decoded_line = line.decode('utf-8', errors='ignore').strip()
                    print(f"[websocket_server] {decoded_line}")
            except Exception as e:
                print(f"读取websocket_server输出时出错: {e}")
        
        if process.poll() != 0:
            print(f"警告: websocket_server.py进程异常退出，返回代码: {process.returncode}")
    
    # 启动监控线程
    monitor_thread = threading.Thread(target=monitor_output)
    monitor_thread.daemon = True
    monitor_thread.start()
    
    return process

# 主函数
def main():
    print("=== 手机投屏服务管理器 ===")
    print("正在启动所有必要的服务...")
    
    # 确保stream目录存在
    stream_dir = os.path.join(PROJECT_DIR, 'stream')
    if not os.path.exists(stream_dir):
        os.makedirs(stream_dir)
        print(f"已创建流目录: {stream_dir}")
    
    # 启动所有服务
    processes = []
    
    # 启动HTTP服务器（在单独的线程中）
    http_thread = threading.Thread(target=start_http_server)
    http_thread.daemon = True
    http_thread.start()
    
    # 启动WebSocket服务器
    websocket_process = start_websocket_server()
    if websocket_process:
        processes.append(websocket_process)
    
    # 等待WebSocket服务器启动
    time.sleep(1)
    
    # 启动simple_stream.py
    simple_stream_process = start_simple_stream()
    if simple_stream_process:
        processes.append(simple_stream_process)
    
    # 提示用户
    print("=== 所有服务已启动 ===")
    print(f"请在浏览器中访问: http://localhost:{HTTP_PORT}")
    print("按 Ctrl+C 停止所有服务...")
    
    try:
        # 保持主进程运行
        while True:
            time.sleep(1)
    except KeyboardInterrupt:
        print("\n正在停止所有服务...")
    finally:
        # 停止所有进程
        for process in processes:
            try:
                process.terminate()
            except Exception:
                pass
        
        print("所有服务已停止")

if __name__ == "__main__":
    main()